# -*- encoding:utf-8 -*-
from paddleocr import PaddleOCR, draw_ocr

import os 
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

# Paddleocr目前支持i的多语言语种可以通过修改lang参数进行切换
# 例如`ch`, `en`, `fr`, `german`, `korean`, `japan`
ocr = PaddleOCR(use_angle_cls=True, lang="ch" ,use_gpu=False)  # need to run only once to download and load model into memory
def get_imgae_content(img_path):
    content= []
    result = ocr.ocr(img_path, cls=True)
    for line in result:
        if len(line[-1][0])>1:
           content.append(line[-1][0])
        # print(line)
    return '##'.join(content)



# 显示结果
def show_results(img_path):
    from PIL import Image
    result = ocr.ocr(img_path, cls=True)
    image = Image.open(img_path).convert('RGB')
    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]
    im_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)
    save_path = os.path.splitext(img_path)[0]
    im_show.save(save_path+'-result.jpg')


if __name__ == '__main__':
    img_path = './imgs/image1.jpg'
    img_path = 'ocr/imgs/v2-3124ec41bd450b2a677030245f76b189_1440w.jpg'
    for root , dirs,files in os.walk("./imgs"):
        for img_name in files:
            img_path = os.path.join(root,img_name)
            show_results(img_path)
            content =get_imgae_content(img_path)
            fmt = "====\nImgae:{}\nContent:{}\n====".format(img_path,content)
            print(fmt)
        
    def parse_image(img_pth):
        show_results(img_path)
        content =get_imgae_content(img_path)
        fmt = "====\nImgae:{}\nContent:{}\n====".format(img_path,content)
        print(fmt)
